import {DirectiveBinding} from 'vue';
import {useUserStore} from '@/store/user';

export const permission = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string | string[]>) {
    const userStore = useUserStore();
    const permissionList = userStore.permissionList;
    let isPermission = false;
    const {value, modifiers} = binding;

    // 判断是否有权限
    if (modifiers.some) {
      isPermission = permissionList.some(item => value.includes(item));
    } else if (modifiers.every) {
      isPermission = permissionList.every(item => value.includes(item));
    } else {
      isPermission = permissionList.includes(value as string);
    }

    if (isPermission && el.parentNode) {
      el.parentNode.removeChild(el);
    }
  }
};

/** 判断是否有权限 */
export function hasPermission(value: string | IPermissionParamsSome | IPermissionParamsEvery) {
  const userStore = useUserStore();
  const permissionList = userStore.permissionList;
  let isPermission = false;

  if (value.hasOwnProperty('some')) {
    isPermission = permissionList.some(item => (value as IPermissionParamsSome).some.includes(item));
  } else if (value.hasOwnProperty('every')) {
    isPermission = permissionList.every(item => (value as IPermissionParamsEvery).every.includes(item));
  } else {
    isPermission = permissionList.includes(value as string);
  }

  return isPermission;
}

export interface IPermissionParamsSome {
  some: string[];
}
export interface IPermissionParamsEvery {
  every: string[];
}
